package com.ibeetl.admin.aod.web;

import com.ibeetl.admin.aod.entity.AodIndustryKeyword;
import com.ibeetl.admin.aod.service.AodIndustryKeywordService;
import com.ibeetl.admin.aod.service.excel.processor.AodIndustryKeywordImportProcessor;
import com.ibeetl.admin.aod.web.query.AodIndustryKeywordQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * AodIndustryKeyword 接口
 */
@Controller
public class AodIndustryKeywordController extends BaseController {

    private static final String MODEL = "/aod/aodIndustryKeyword";

    @Autowired
    private AodIndustryKeywordService aodIndustryKeywordService;

    @Autowired
    private AodIndustryKeywordImportProcessor aodIndustryKeywordImportProcessor;

    @Autowired
    FileService fileService;

    @GetMapping(MODEL + "/index.do")
    @Function("aodIndustryKeyword.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/aod/aodIndustryKeyword/index.html") ;
        view.addObject("search", AodIndustryKeywordQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("aodIndustryKeyword.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/aod/aodIndustryKeyword/edit.html");
        AodIndustryKeyword aodIndustryKeyword = aodIndustryKeywordService.queryById(id);
        view.addObject("aodIndustryKeyword", aodIndustryKeyword);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("aodIndustryKeyword.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/aod/aodIndustryKeyword/add.html");
        return view;
    }

    @PostMapping(MODEL + "/list.json")
    @Function("aodIndustryKeyword.query")
    @ResponseBody
    public JsonResult<PageQuery> list(AodIndustryKeywordQuery condition) {
        PageQuery page = condition.getPageQuery();
        aodIndustryKeywordService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/listAll.json")
    @Function("aodIndustryKeyword.query")
    @ResponseBody
    public JsonResult<PageQuery> listAll(AodIndustryKeywordQuery condition) {
        PageQuery page = condition.getPageQuery();
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        aodIndustryKeywordService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("aodIndustryKeyword.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)AodIndustryKeyword aodIndustryKeyword) {
        aodIndustryKeywordService.saveUnique(aodIndustryKeyword);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("aodIndustryKeyword.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  AodIndustryKeyword aodIndustryKeyword) {
        aodIndustryKeywordService.updateUnique(aodIndustryKeyword);
        return new JsonResult().success();
    }

    @GetMapping(MODEL + "/view.json")
    @Function("aodIndustryKeyword.query")
    @ResponseBody
    public JsonResult<AodIndustryKeyword>queryInfo(Integer id) {
        AodIndustryKeyword aodIndustryKeyword = aodIndustryKeywordService.queryById( id);
        return  JsonResult.success(aodIndustryKeyword);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("aodIndustryKeyword.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        aodIndustryKeywordService.batchDelAodIndustryKeyword(idList);
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("aodIndustryKeyword.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,AodIndustryKeywordQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此aodIndustryKeywordService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/aod/aodIndustryKeyword/aodIndustryKeyword_export_template.xls";
        PageQuery<AodIndustryKeyword> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<AodIndustryKeyword> list =aodIndustryKeywordService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("AodIndustryKeyword_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("aodIndustryKeyword.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            aodIndustryKeywordImportProcessor.process(file, "excelTemplates/aod/aodIndustryKeyword/aodIndustryKeyword_mapping.xml");
            return JsonResult.success();
        } catch (Exception e) {
            log.error("导入行业关键词出错",e);
            return JsonResult.failMessage(e.getMessage());
        }
    }



}
